//用户导入导出等
/**
 * @openapi
 * tags:
 * - name: admin/user
 *   description: 用户数据处理
 */

const router = require("express-promise-router")();

const multer  = require('multer');
const config=require("../../config/config");
const template_file = config.template_file;
const tmp_uploads_dir=config.tmp_uploads_dir; //存放临时上传的文件。导入完成后就可以删除。不做hash处理
const upload = multer({ dest: tmp_uploads_dir });
//console.log('tmp_uploads_dir',tmp_uploads_dir);


const UserService = require("../../services/user");
const LogService = require("../../services/log");

/**
 *
 * @openapi
 * /teacher/user/reset_password:
 *   post:
 *     tags:
 *     - admin/user
 *     summary: 重置密码
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               username:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 重置成功，密码和用户名相同
 *       400:
 *         description: 失败
 */
//重置密码
router.post('/reset_password',async function(req, res) {
    const user=req.session.user;
    if(!user.isAdmin){
        return res.status(401).send("只有管理员才能重置密码");
    }
    const {username}=req.body;
    try{
        await UserService.reset_password(username);
        LogService.addLog(user,"用户",`重置用户密码：${username}`);
        res.end();//成功 200
    }catch (e) {
        res.status(400).send({error:e.toString()}); //失败 400,返回{error:"..."}
    }
});


/**
 * @openapi
 * /teacher/user/import/check_file:
 *   post:
 *     tags:
 *     - admin/user
 *     summary: 导入用户第一步，检查excel文件
 *     requestBody:
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *               nameRowNumber:
 *                 type: number
 *               firstDataRowNumber:
 *                 type: number
 *               fieldsMapping:
 *                 type: object
 *     responses:
 *       200:
 *         description: 返回JSON文件信息
 */
//从excel文件导入用户，可传递标题行与数据开始行，可以传递一个表头映射对象
router.post('/import/check_file', upload.single('file'), async function  (req, res){
    // req.file 是 `users` 文件的信息
    // req.body 将具有文本域数据，如果存在的话
    //req.file.path 是文件路径
    var default_nameRowNumber = 1;
    var default_firstDataRowNumber = 2;
    if(template_file==='users_kmust.xlsx'){
        default_nameRowNumber = 5;
        default_firstDataRowNumber = 6;
    }
    let {nameRowNumber=default_nameRowNumber,firstDataRowNumber=default_firstDataRowNumber,fieldsMapping}=req.body;
    if(fieldsMapping){
        fieldsMapping=JSON.parse(fieldsMapping);
    }
    //检查Excel文件是否合乎格式
    const result=await UserService.checkExcelFile(req.file.path,nameRowNumber,firstDataRowNumber,fieldsMapping);
    if(result.error){
        return res.status(400).send({"error":result.error});
    }else{
        return res.json(result);
    }
});

/*
{
  "filePath": "C:\\x_项目\\lims_v5\\tmp_uploads\\5ab1bed9b851ff3be2eec9cfc7023b73",
  "nameRowNumber": 6,
  "firstDataRowNumber": 7,
  "fieldsMapping": {"学号":"username"}
}
* */
/**
 * @openapi
 * /teacher/user/import/confirm_file:
 *   post:
 *     tags:
 *     - admin/user
 *     summary: 导入用户第二步，确认导入excel文件
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               filePath:
 *                 type: string
 *               nameRowNumber:
 *                 type: number
 *               firstDataRowNumber:
 *                 type: number
 *               fieldsMapping:
 *                 type: object
 *       required: true
 *     responses:
 *       200:
 *         description: 返回md5处理的字符串
 */
router.post('/import/confirm_file',  async function  (req, res){
    //从客户端取得要导入的文件路径，由check_file给出
    var default_nameRowNumber = 1;
    var default_firstDataRowNumber = 2;
    if(template_file==='users_kmust.xlsx'){
        default_nameRowNumber = 5;
        default_firstDataRowNumber = 6;
    }
    let {nameRowNumber=default_nameRowNumber,firstDataRowNumber=default_firstDataRowNumber,filePath,fieldsMapping}=req.body;
    // if(fieldsMapping){
    //     fieldsMapping=JSON.parse(fieldsMapping);
    // }
    //导入到数据库
    const result=await UserService.importExcelFile(filePath,nameRowNumber,firstDataRowNumber,fieldsMapping);
    LogService.addLog(req.session.user,"用户",`导入用户`);
    res.json(result);
});

//批量更新用户
/**
 * users=[{username,field1,field2,...}]
 */
/**
 * @openapi
 * /teacher/user/update_users:
 *   post:
 *     tags:
 *     - admin/user
 *     summary: 批量更新用户，username必须有，其他字段可以自定义添加
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: array
 *             items:
 *               type: object
 *               properties:
 *                 username:
 *                   type: string
 *                 showName:
 *                   type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回更新的用户数量
 */
router.post('/update_users',  async function  (req, res){
    const {users}=req.body;
    const result=await UserService.batchUpdateUsers(users);
    LogService.addLog(req.session.user,"用户",`批量更新用户`);
    res.json(result);
});

/**
 *
 * @openapi
 * /teacher/user/remove:
 *   post:
 *     tags:
 *     - teacher/user
 *     summary: 移除用户
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               objectId:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 移除成功
 *       400:
 *         description: 失败
 */
//移除用户
router.post('/remove',async function(req, res) {
    const {objectId}=req.body;
    try{
        await UserService.remove(objectId);
        LogService.addLog(req.session.user,"删除",`删除用户：${objectId}`);
        res.end();//成功 200
    }catch (e) {
        res.status(400).send({error:e.toString()}); //失败 400,返回{error:"..."}
    }
});



module.exports = router;
